package com.todo.biz.application.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.biz.application.convert.CollectConvert;
import com.todo.biz.common.base.BizBaseKeyBuild;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.biz.infrastructure.entity.po.CollectRelationPO;
import com.todo.common.common.exception.BizException;
import com.todo.component.redis.RedisService;
import com.todo.biz.infrastructure.repository.CollectRelationRepository;

import com.todo.biz.application.service.CollectRelationService;
import com.todo.biz.application.entity.bo.CollectRelationBO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (CollectRelation)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:44
 */
@Slf4j
@Service("collectRelationService")
public class CollectRelationServiceImpl implements CollectRelationService {

    @Resource
    private CollectRelationRepository collectRelationRepository;
    @Resource
    private RedisService redisService;

    @Override
    public Boolean batchInsertCollectRelation(List<CollectRelationBO> collectRelationBOList) {
        if (CollectionUtils.isEmpty(collectRelationBOList)) {
            return true;
        }
        if (collectRelationBOList.size() > 100) {
            log.error("CollectRelationService#batchInsertCollectRelation 批量新增集合关联信息，参数异常，参数长度大于1000，collectRelationBOList：【{}】", JSONObject.toJSONString(collectRelationBOList));
            throw new BizException(BizErrorCodeEnum.QUANTITY_EXPLOSION);
        }
        //剔除重复数据
        List<CollectRelationBO> collect = collectRelationBOList.stream().distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return true;
        }
        List<CollectRelationPO> collectRelationPOList = CollectConvert.convertToCollectRelationPOList(collect);
        Boolean updated = collectRelationRepository.batchInsertCollectRelation(collectRelationPOList);
        if (updated) {
            String setRelationKey = BizBaseKeyBuild.getCollectRelationKey(collect.get(0).getSetId());
            for (CollectRelationBO collectRelationBO : collect) {
                redisService.hSet(setRelationKey, String.valueOf(collectRelationBO.getRelationId()), JSONObject.toJSONString(collectRelationBO));
            }
        }
        return updated;
    }


    @Override
    public Boolean removeCollectRelationBySetId(Long setId) {
        if (setId == null || setId < 0) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        Integer count = collectRelationRepository.queryCountBySetId(setId);
        if (count == 0) {
            log.info("CollectRelationService#removeCollectRelationById 根据主键id删除集合关联完成，查询数据为空，默认删除成功 setId：【{}】", setId);
            return true;
        }
        Integer removeCount = collectRelationRepository.removeCollectRelationBySetId(setId);
        if (removeCount > 0) {
            String setRelationKey = BizBaseKeyBuild.getCollectRelationKey(setId);
            redisService.del(setRelationKey);
        }
        return removeCount > 0;
    }


    @Override
    public List<CollectRelationBO> queryCollectRelationBOBySetId(Long setId) {
        if (setId == null || setId < 0) {
            return Collections.emptyList();
        }
        String setRelationKey = BizBaseKeyBuild.getCollectRelationKey(setId);
        Map<String, String> cacheMap = redisService.hGetAll(setRelationKey);
        List<CollectRelationBO> result = new ArrayList<>();
        if (MapUtils.isNotEmpty(cacheMap)) {
            for (String key : cacheMap.keySet()) {
                CollectRelationBO collectRelationBO = JSONObject.parseObject(cacheMap.get(key), CollectRelationBO.class);
                if (collectRelationBO != null) {
                    result.add(collectRelationBO);
                }
            }
            return result;
        }


        List<CollectRelationPO> collectRelationPOS = collectRelationRepository.queryCollectRelationListBySetId(setId);
        if (CollectionUtils.isEmpty(collectRelationPOS)) {
            log.warn("CollectRelationService#queryCollectRelationBOBySetId 根据集合id查询关联数据列表为空 setId：【{}】", setId);
            return Collections.emptyList();
        }
        List<CollectRelationBO> collect = collectRelationPOS.stream().map(CollectConvert::convertToCollectRelationBO).collect(Collectors.toList());
        for (CollectRelationBO collectRelationBO : collect) {
            redisService.hSet(setRelationKey, String.valueOf(collectRelationBO.getId()), JSONObject.toJSONString(collectRelationBO));
        }
        return collect;
    }

    @Override
    public List<Long> querySetIdListByRelationId(Long relationId) {
        if (relationId == null || relationId < 0) {
            return Collections.emptyList();
        }
        List<Long> setIdList = collectRelationRepository.querySetIdListByRelationId(relationId);
        return setIdList;
    }

    @Override
    public CollectRelationBO queryCollectRelationBOById(Long id) {
        if (id == null || id < 0) {
            return null;
        }
        CollectRelationPO collectRelationPO = collectRelationRepository.queryCollectRelationPOById(id);
        CollectRelationBO collectRelationBO = CollectConvert.convertToCollectRelationBO(collectRelationPO);
        return collectRelationBO;
    }
}
